<template>
  <!-- MemberAudit 会员审核 -->
  <PageContainer>
    <view class="container">
      <Tabs v-model="currentTab">
        <Header
          title="会员审核"
          :is-box-shadow="false"
          :z-index="headerZindex"
          v-model="headerHeight"
        >
          <TabNav tabBarColor="#D7B87C" />
          <view class="w-screen disFlxJS">
            <view class="bg-white flex-1" style="width: 90%">
              <RadioTagGroup
                v-if="currentTab === 0"
                v-model="memberApplyFormParame.filterTerm"
                :data="memberApplyFormFilter"
                @change="memberApplyFormFilterChange"
              >
                <YFilter
                  ref="filterRef"
                  :headerHeight="headerHeight"
                  @submit="filterSubmit"
                  :z-index="headerZindex"
                ></YFilter>
              </RadioTagGroup>
              <RadioTagGroup
                v-else-if="currentTab === 1"
                v-model="memberInfoApplyParame.filterTerm"
                :data="memberInfoApplyFilter"
                @change="memberInfoApplyFilterChange"
              >
                <YFilter
                  ref="filterRef"
                  :headerHeight="headerHeight"
                  @submit="filterSubmit"
                  :z-index="headerZindex"
                ></YFilter>
              </RadioTagGroup>
              <RadioTagGroup
                v-else-if="currentTab === 2"
                v-model="paymentRecordParame.filterTerm"
                :data="paymentRecordFilter"
                @change="paymentRecordChange"
              />
            </view>
            <!-- <view v-if="currentTab !== 2" class="flex-shrink-0 w-18">
              <YFilter
                ref="filterRef"
                :headerHeight="headerHeight"
                @submit="filterSubmit"
                :z-index="headerZindex"
              ></YFilter>
            </view> -->
          </view>
        </Header>
        <TabsItem
          v-if="checkRouterPermission('membershipReview', true)"
          name="入会审核"
          :value="0"
          :unread="getMemberApplyFormUnread"
        >
          <Paglist
            v-model="applyForData"
            :is-init-api="false"
            :parame="memberApplyFormParame"
            @register="memberApplyFormRegister"
            :is-show-loadmore="applyForData.length > 1"
            :scroll-top-bottom="200"
          >
            <template v-for="v in applyForData" :key="v.id">
              <MemberItem
                :item="{
                  id: v.id,
                  createTime: v.createTime,
                  applyType: v.applyType,
                  isFinish: v.isFinish,
                  paymentStatus: v.paymentStatus,
                  auditStatus: v.auditStatus,
                  memberName: v.proposer,
                  levelId: v.levelId,
                  levelName: v.levelName,
                  membershipFees: v.membershipFees,
                  memberId: v.memberId,
                  isSetPaymenrecord: v.isSetPaymenrecord,
                }"
                :show-status="true"
                :show-btn="true"
                :content-table="[
                  {
                    label: '会员类型：',
                    value:
                      applyTypeDicts.find((dict) => dict.dictValue === v.applyType)?.dictLabel ??
                      '',
                  },
                  {
                    label: '申请职务：',
                    value: v.levelName,
                  },
                  {
                    label: '审核阶段：',
                    value: v.stageName,
                  },
                  {
                    label: '申请人：',
                    value: v.userName,
                  },
                  {
                    label: '申请时间：',
                    value: v.createTime,
                    isRightText: true,
                  },
                ]"
                detailsPath="memberApplyFormAudit"
                @show-contact-way="showContactWay(v)"
                @refresh="memberApplyFormRefresh"
              />
            </template>
          </Paglist>
        </TabsItem>
        <TabsItem
          v-if="checkRouterPermission('memberInfoChanges', true)"
          name="资料变更"
          :value="1"
          :unread="memberInfoApplyUnread"
        >
          <Paglist
            v-model="changeData"
            :is-init-api="false"
            :parame="memberInfoApplyParame"
            @register="memberInfoApplyListRegister"
            :is-show-loadmore="changeData.length > 1"
            :scroll-top-bottom="200"
          >
            <template v-for="v in changeData" :key="v.id">
              <MemberItem
                :item="{
                  id: v.id,
                  createTime: v.createTime,
                  applyType: v.applyType,
                  auditStatus: v.auditStatus,
                  memberName: v.memberName,
                  levelName: v.levelName,
                  memberId: v.memberId,
                }"
                :show-status="true"
                :show-btn="true"
                :content-table="[
                  {
                    label: '会员类型：',
                    value:
                      applyTypeDicts.find((dict) => dict.dictValue === v.applyType)?.dictLabel ??
                      '',
                  },
                  {
                    label: '会员职务：',
                    value: v.levelName,
                  },
                  {
                    label: '提交人：',
                    value: v.submitName,
                    phoneNumber: v.submitPhone,
                  },
                  {
                    label: '提交时间：',
                    value: v.createTime,
                    isRightText: true,
                  },
                ]"
                details-path="memberInfoApplyAudit"
                @show-contact-way="showContactWay(v)"
                @refresh="memberInfoApplyListRefresh"
              />
            </template>
          </Paglist>
        </TabsItem>
        <TabsItem
          v-if="checkRouterPermission('renewalVoucher', true)"
          name="续费凭证"
          :value="2"
          :unread="paymentRecordUnread"
        >
          <Paglist
            v-model="payData"
            :is-init-api="false"
            :parame="paymentRecordParame"
            @register="paymentRecordListRegister"
            :is-show-loadmore="payData.length > 1"
            :scroll-top-bottom="200"
          >
            <template v-for="v in payData" :key="v.id">
              <MemberItem
                :item="{
                  id: v.id,
                  createTime: v.submitTime,
                  applyType: v.applyType,
                  auditStatus: v.auditStatus,
                  memberName: v.memberName,
                  levelName: v.levelName,
                  memberId: v.memberId,
                }"
                :show-status="true"
                :show-btn="true"
                :content-table="[
                  {
                    label: '本期职务：',
                    value: v.nowLevelName,
                  },
                  {
                    label: '续费金额：',
                    value: v.payMoney + '元',
                  },
                  {
                    label: '凭证提交人：',
                    value: v.submitName,
                    phoneNumber: v.submitPhone,
                  },
                  {
                    label: '提交时间：',
                    value: v.submitTime,
                    isRightText: true,
                  },
                ]"
                details-path="memberRenewAudit"
                @show-contact-way="showContactWay(v)"
                @refresh="paymentRecordListRefresh"
              />
            </template>
          </Paglist>
        </TabsItem>
      </Tabs>
      <UniPopup ref="contactWay">
        <view class="contact-way">
          <view class="contact-way__title">
            <text>拨打电话</text>
          </view>
          <view class="contact-way__content">
            <template v-for="(v, i) in contactWayList" :key="i">
              <view
                v-if="v.name && v.phone"
                class="contact-way__item"
                @click="makePhoneCall(v.phone)"
              >
                <view class="item-info">
                  <view class="item-info__name text-overflow-1">{{ v.label }}: {{ v.name }}</view>
                  <view class="item-info__phone">{{ v.phone }}</view>
                </view>
                <view class="ali-icon">&#xe678;</view>
              </view>
            </template>
          </view>
        </view>
      </UniPopup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  MemberAudit  会员审核 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import type {
    MemberApplyFormResult,
    MemberInfoApplyResult,
    IRenewOfflineMemberOrderListResult,
    IFormParame,
  } from '@/api/admin/types';
  import Header from '@/components/Header/index.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import { getCurrentInstance, provide, reactive, ref, watch, computed } from 'vue';
  import MemberItem from './components/MemberItem.vue';
  import Dictionary from '@/utils/dictionary';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import {
    memberApplyFormList,
    memberInfoApplyList,
    RenewOfflineMemberOrderList,
    sysMemberAuditStatistics,
  } from '@/api/admin';
  import { onLoad } from '@/router';
  import { onPageScroll, onPullDownRefresh, onShow, onUnload } from '@dcloudio/uni-app';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';
  import RadioTagGroup, { type TagItem } from '../components/RadioTagGroup.vue';
  import { useUserStore } from '@/store/modules/user';
  import YFilter from './components/YFilter.vue';
  import { AuditStatusEnum } from '@/enums/membershipEnum';
  const { checkRouterPermission } = useUserStore();

  const applyTypeDicts = Dictionary.getLocal('memberType');
  const headerZindex = ref(999);
  const currentTab = ref(0);
  const headerHeight = ref(0);

  const applyForData = ref<MemberApplyFormResult[]>([]);
  const getMemberApplyFormUnread = computed(() => {
    const d = memberApplyFormFilter.value;
    const n1 = d[1].num || 0;
    const n2 = d[2].num || 0;
    return n1 + n2;
  });

  const memberApplyFormParame = reactive<IFormParame>({
    filterTerm: 0,
    applyTypeList: undefined,
    levelIds: undefined,
  });
  const memberApplyFormFilter = ref<TagItem[]>([
    { value: 0, label: '全部' },
    { value: 1, label: '待审核' },
    { value: 2, label: '待缴费' },
    { value: 3, label: '入会完成' },
    { value: 4, label: '已驳回' },
  ]);
  function memberApplyFormFilterChange() {
    memberApplyFormRefresh();
  }
  const [memberApplyFormRegister, { refresh: memberApplyFormRefresh }] = useConList({
    api: memberApplyFormList,
  });

  const changeData = ref<MemberInfoApplyResult[]>([]);
  const memberInfoApplyUnread = ref(0);
  const memberInfoApplyParame = reactive<IFormParame>({
    filterTerm: 0,
    applyTypeList: undefined,
    levelIds: undefined,
  });
  const memberInfoApplyFilter = ref<TagItem[]>([
    { value: 0, label: '全部' },
    { value: 1, label: '资料待审核' },
    { value: 2, label: '已通过' },
    { value: 3, label: '已驳回' },
  ]);
  function memberInfoApplyFilterChange() {
    memberInfoApplyListRefresh();
  }
  const [memberInfoApplyListRegister, { refresh: memberInfoApplyListRefresh }] = useConList({
    api: memberInfoApplyList,
  });

  const payData = ref<IRenewOfflineMemberOrderListResult[]>([]);
  const paymentRecordUnread = ref(0);
  const paymentRecordParame = reactive({
    filterTerm: 0,
  });
  const paymentRecordFilter = ref<TagItem[]>([
    { value: 0, label: '全部' },
    { value: 1, label: '凭证待审核' },
    { value: 2, label: '已通过' },
    { value: 3, label: '已驳回' },
  ]);

  function filterSubmit(params: IFormParame) {
    if (currentTab.value === 0) {
      memberApplyFormParame.applyTypeList = params.applyTypeList;
      memberApplyFormParame.levelIds = params.levelIds;
      memberApplyFormRefresh();
    } else if (currentTab.value === 1) {
      memberInfoApplyParame.applyTypeList = params.applyTypeList;
      memberInfoApplyParame.levelIds = params.levelIds;
      memberInfoApplyFilterChange();
    }
  }
  function paymentRecordChange() {
    paymentRecordListRefresh();
  }
  const [paymentRecordListRegister, { refresh: paymentRecordListRefresh }] = useConList({
    api: RenewOfflineMemberOrderList,
  });

  const filterRef = ref<InstanceType<typeof YFilter>>();
  watch(currentTab, (val) => {
    tabsChange(val);
    filterRef.value?.restFnc();
  });

  function tabsChange(index: number) {
    switch (index) {
      case 0:
        !applyForData.value.length && memberApplyFormRefresh();
        break;
      case 1:
        !changeData.value.length && memberInfoApplyListRefresh();
        break;
      case 2:
        !payData.value.length && paymentRecordListRefresh();
        break;
    }
  }

  const _this = getCurrentInstance();

  const contactWayList = ref<{ label: string; name: string; phone: string }[]>([]);

  function showContactWay(item: any) {
    const {
      contactPersonName,
      contactPersonPhone,
      userName,
      phonenumber,
      submitName,
      submitPhone,
    } = item;
    contactWayList.value = [
      {
        label: currentTab.value === 0 ? '申请人' : '提交人',
        name: userName || submitName,
        phone: phonenumber || submitPhone,
      },
      {
        label: '负责人',
        name: contactPersonName,
        phone: contactPersonPhone,
      },
    ];
    openPopup();
  }

  const openPopup = (ref: string = 'contactWay', direction: string = 'center') => {
    (_this?.refs[ref] as any).open(direction);
  };

  const closePopup = (ref: string = 'contactWay', direction: string = 'center') => {
    (_this?.refs[ref] as any).close(direction);
  };

  function makePhoneCall(phone: string) {
    uni.makePhoneCall({ phoneNumber: phone, success: () => closePopup() });
  }

  function getSysMemberAuditStatistics() {
    sysMemberAuditStatistics().then((r) => {
      memberApplyFormFilter.value[1].num = r.memberApplyAuditStatisticsVo.auditNumber;
      memberApplyFormFilter.value[2].num = r.memberApplyAuditStatisticsVo.unpaidPaymentNumber;
      memberInfoApplyUnread.value = r.infoAuditNumber;
      paymentRecordUnread.value = r.renewAuditNumber;
    });
  }

  onShow(() => {
    getSysMemberAuditStatistics();
  });

  onPullDownRefresh(() => {
    getSysMemberAuditStatistics();
  });

  onLoad(() => {
    if (checkRouterPermission('membershipReview')) {
      currentTab.value = 0;
      tabsChange(0);
    } else if (checkRouterPermission('memberInfoChanges')) {
      currentTab.value = 1;
      tabsChange(1);
    } else {
      currentTab.value = 2;
      tabsChange(2);
    }
    uni.$on(UniEmitNameEnum.REFRESHPREVIOUSPAGE, () => {
      memberApplyFormRefresh();
    });
  });

  onUnload(() => {
    uni.$off(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
  });

  provide('api', undefined);
  onPageScroll(() => {});
</script>

<style lang="scss" scoped>
  .contact-way {
    background-color: #fff;
    width: calc(100vw - 60rpx);
    border-radius: 20rpx;
    &__title {
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      color: #333;
      font-weight: bolder;
      font-size: 32rpx;
    }
    &__item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 40rpx;
      padding: 30rpx 0;
      border-bottom: 1px solid #dddddd;
      .item-info {
        &__name {
          color: #333;
          font-size: 32rpx;
          margin-bottom: 12rpx;
        }
        &__phone {
          color: #aaabab;
          font-size: 28rpx;
        }
      }
      .ali-icon {
        font-size: 40rpx;
        transform: rotateZ(270deg);
      }
    }
  }
</style>
